package nc.impl.ia.report.detailledger.goods;

import com.ufida.dataset.IContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import nc.bs.ia.pub.ReportDataUtil;
import nc.bs.ml.NCLangResOnserver;
import nc.bs.scmpub.report.ReportQueryCondition;
import nc.impl.pubapp.pattern.data.mapping.ViewRowSetMap;
import nc.impl.pubapp.pattern.database.DataAccessUtils;
import nc.impl.pubapp.pattern.page.SecondaryPage;
import nc.itf.ia.report.goodsledger.IGoodsLedgerReport;
import nc.itf.scmpub.reference.fip.FipBillQueryService;
import nc.pub.smart.data.DataSet;
import nc.pub.smart.metadata.Field;
import nc.pub.smart.metadata.MetaData;
import nc.vo.fip.service.FipRelationInfoVO;
import nc.vo.ia.enumeration.FCalcBizFlag;
import nc.vo.ia.enumeration.FIntransitFlag;
import nc.vo.ia.enumeration.FPriceModeFlag;
import nc.vo.ia.pub.page.PageInfo;
import nc.vo.ia.pub.period.AccountPeriod;
import nc.vo.ia.pub.period.Calendar;
import nc.vo.ia.pub.util.IAScaleUtil;
import nc.vo.ia.pub.util.SQLUtil;
import nc.vo.ia.pub.util.VOValueUtil;
import nc.vo.ia.report.detailledger.DetailLedgerViewMeta;
import nc.vo.ia.report.goodsledger.GoodsLedgerViewMeta;
import nc.vo.ia.report.goodsledger.GoodsLedgerViewVO;
import nc.vo.ia.report.pub.IAReportUtil;
import nc.vo.ia.report.storledger.StorLedgerViewMeta;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pub.query.ConditionVO;
import nc.vo.pubapp.pattern.data.IRowSet;
import nc.vo.pubapp.pattern.data.ValueUtils;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.model.meta.entity.view.IDataViewMeta;
import nc.vo.pubapp.pattern.pub.MathTool;
import nc.vo.pubapp.pattern.pub.PubAppTool;
import nc.vo.pubapp.pattern.pub.SqlBuilder;
import nc.vo.pubapp.report.ReportQueryConUtil;
import nc.vo.scmpub.page.ViewDBPage;






public class GoodsLedgerReportImpl
  implements IGoodsLedgerReport
{
  public GoodsLedgerViewVO[] queryFHDDetail(ReportQueryCondition condition, String cdetailledgerid) throws BusinessException {
    GoodsLedgerViewVO[] ret = null;
    try {
      String ccalcthreadid = getThreadID(cdetailledgerid);
      ret = queryFHDDetailVOs(condition, ccalcthreadid);
      calculateFHDDetail(ret);
    }
    catch (Exception e) {
      ExceptionUtils.marsh(e);
    } 
    return ret;
  }

  
  public DataSet queryGoodsLedger(IContext context) throws BusinessException {
    DataSet dataset = new DataSet();
    try {
      
      ReportQueryConUtil qryconutil = new ReportQueryConUtil(context);
      
      if (!qryconutil.isNull()) {
    	  dataset.setMetaData(getMetaData());
        ConditionVO[] convos = (ConditionVO[])qryconutil.getUserObject();
        GoodsLdgConProcess querycon = new GoodsLdgConProcess(convos);
        if (context.getAttribute("wheresql") != null) {
          
          String wheresql = context.getAttribute("wheresql").toString();
          String consql = getWheresql(wheresql);
          querycon.setWheresql(consql);
        } 
        GoodsLdgDataProcess goodsldgdata = new GoodsLdgDataProcess(querycon);
        
        queryBeginData(querycon, goodsldgdata);
        
        queryYearInOutData(querycon, goodsldgdata);
        
        queryGoodsLedgerData(dataset, querycon, goodsldgdata);
      }else {
    	  dataset.setMetaData(getMetaData2());
      }
    
    } catch (Exception e) {
      ExceptionUtils.marsh(e);
    } 
    
    return dataset;
  }
  
  private void calculateFHDDetail(GoodsLedgerViewVO[] ret) {
    if (ret.length == 0) {
      return;
    }
    UFDouble nabnum = null;
    UFDouble nabmny = null;
    UFDouble nabvarymny = null;
    
    for (GoodsLedgerViewVO vo : ret) {
      Integer fintransitflag = vo.getFintransitflag();
      Integer fpricemodeflag = vo.getFpricemodeflag();
      UFDouble nnum = vo.getNnum();
      UFDouble nprice = vo.getNprice();
      UFDouble nmny = vo.getNmny();
      
      UFDouble varymny = null;
      if (fpricemodeflag.equals(FPriceModeFlag.JHJ.value()) || fpricemodeflag
        .equals(FPriceModeFlag.BZCB.value())) {
        varymny = vo.getNvarymny();
        nmny = MathTool.sub(nmny, varymny);
        if (!MathTool.isZero(MathTool.nvl(nnum))) {
          nprice = IAScaleUtil.getScaleUtils().adjustPriceScale(nmny.div(nnum));
        }
      } 
      
      if (FIntransitFlag.DEBIT.equalsValue(fintransitflag)) {
        vo.setNdebitnum(nnum);
        vo.setNdebitprice(nprice);
        vo.setNdebitmny(nmny);
        
        nabnum = MathTool.add(nabnum, nnum);
        nabmny = MathTool.add(nabmny, nmny);
        if (fpricemodeflag.equals(FPriceModeFlag.JHJ.value()) || fpricemodeflag
          .equals(FPriceModeFlag.BZCB.value())) {
          vo.setNdebitvarymny(varymny);
          nabvarymny = MathTool.add(nabvarymny, varymny);
        } 
      } else {
        
        vo.setNcreditnum(nnum);
        vo.setNcreditprice(nprice);
        vo.setNcreditmny(nmny);
        
        nabnum = MathTool.sub(nabnum, nnum);
        nabmny = MathTool.sub(nabmny, nmny);
        if (fpricemodeflag.equals(FPriceModeFlag.JHJ.value()) || fpricemodeflag
          .equals(FPriceModeFlag.BZCB.value())) {
          vo.setNcreditvarymny(varymny);
          nabvarymny = MathTool.sub(nabvarymny, varymny);
        } 
      } 
      vo.setNabnum(nabnum);
      UFDouble nabprice = null;
      if (nabnum != null && !MathTool.isZero(nabnum))
      {
        nabprice = IAScaleUtil.getScaleUtils().adjustPriceScale(nabmny.div(nabnum));
      }
      vo.setNabprice(nabprice);
      vo.setNabmny(nabmny);
      if (fpricemodeflag.equals(FPriceModeFlag.JHJ.value()) || fpricemodeflag
        .equals(FPriceModeFlag.BZCB.value())) {
        vo.setNabvarymny(nabvarymny);
      }
    } 
  }
  
  private void fillVoucher(GoodsLedgerViewVO[] viewvos) {
    FipRelationInfoVO[] infovos = new FipRelationInfoVO[viewvos.length];
    for (int i = 0; i < viewvos.length; i++) {
      infovos[i] = new FipRelationInfoVO();
      infovos[i].setPk_billtype(viewvos[i].getCbilltypecode());
      infovos[i].setRelationID(viewvos[i].getCdetailledgerid());
      
      infovos[i].setIsIncludeBodys(UFBoolean.FALSE);
    } 
    Map<String, String> map = FipBillQueryService.queryGLVoucherBy(infovos, null);
    for (int i = 0; i < viewvos.length; i++) {
      String voucherno = (String)map.get(viewvos[i].getCdetailledgerid());
      viewvos[i].setVoucher(voucherno);
    } 
  }

  
  private String getDetailSQL(GoodsLdgConProcess gdsldgcon, String accperfrom, String accperto, String detailtable) {
    SqlBuilder sql = new SqlBuilder();
    sql.append("select ");
    sql.append(SQLUtil.joinFileds(GoodsLedgerViewVO.getGoodsPartKeys(), "ia_goodsledger"));
    
    sql.append(",");
    sql.append(SQLUtil.joinFileds(GoodsLedgerViewVO.getDetailPartKeys(), "ia_detailledger"));
    
    sql.append(",");
    sql.append(SQLUtil.joinFileds(IAReportUtil.getRangeKeys(), "ia_calcrange"));
    
    sql.append(" from ia_goodsledger,ia_calcrange,  ");
    sql.append(detailtable + " ia_detailledger  ");
    sql.append(" where ia_goodsledger.dr = 0 ");
    sql.append(" and ia_goodsledger.cdetailledgerid=ia_detailledger.cdetailledgerid");
    
    sql.append(" and ia_goodsledger.ccalcrangeid = ia_calcrange.ccalcrangeid");
    sql.append(" and ia_goodsledger.caccountperiod", ">=", accperfrom);
    sql.append(" and ia_goodsledger.caccountperiod", "<=", accperto);
    sql.append(gdsldgcon.getGoodsldgFilterSql());
    sql.append(gdsldgcon.getGoodsldgDefaultSql());
    
    if (gdsldgcon.getWheresql() != null && !gdsldgcon.getWheresql().contains("ctrantypeid")) {
      sql.append(" and " + gdsldgcon.getWheresql());
    }else if(gdsldgcon.getWheresql() != null && gdsldgcon.getWheresql().contains("ctrantypeid")){
    	String resq = gdsldgcon.getWheresql().replace("ctrantypeid", "ia_goodsledger.ctrantypeid");
        sql.append(" and " + resq);
        }
    return sql.toString();
  }


  
  private String getDetldgQuerySql(GoodsLdgConProcess gdsldgcon, String accperfrom, String accperto) {
    String costorg = gdsldgcon.getPk_org();
    String pk_book = gdsldgcon.getPk_book();
    Calendar calendar = Calendar.getInstance(costorg, pk_book);
    String dumpper = calendar.getLastDumpPeriod();
    
    SqlBuilder sql = new SqlBuilder();
    sql.append("select ");
    sql.append(SQLUtil.joinFileds(GoodsLedgerViewVO.getSelectKeys(), "ia_uniontable"));
    
    sql.append(",");
    sql.append(SQLUtil.joinFileds(IAReportUtil.getRangeKeys(), "ia_uniontable"));
    
    sql.append(" from ");
    String resql1 = sql.toString();
    sql.startParentheses();
    
    if (PubAppTool.isNull(dumpper) || dumpper.compareTo(accperfrom) < 0) {
      sql.append(getDetailSQL(gdsldgcon, accperfrom, accperto, "ia_detailledger"));
      String resql2 = sql.toString();
      String resql10 = sql.toString();
    }
    else if (dumpper.compareTo(accperto) >= 0) {
      sql.append(getDetailSQL(gdsldgcon, accperfrom, accperto, "ia_hisdetailledger"));
      String resql3 = sql.toString();
    }
    else {
      
      AccountPeriod dumpaccper = calendar.getPeriod(dumpper);
      AccountPeriod nextaccper = calendar.getNextPeriod(dumpaccper);
      sql.append(getDetailSQL(gdsldgcon, nextaccper.toString(), accperto, "ia_detailledger"));
      String resq4 = sql.toString();
      
      sql.append(" union all ");
      sql.append(getDetailSQL(gdsldgcon, accperfrom, dumpper, "ia_hisdetailledger"));
      String resq5 = sql.toString();
    } 
    
    if (gdsldgcon.getBinclnoaduit()) {
      sql.append(" union all ");
      sql.append("select ");
      sql.append(SQLUtil.joinFileds(GoodsLedgerViewVO.getSelectKeys(), "ia_detailledger"));
      String resq6 = sql.toString();
      
      sql.append(",");
      sql.append(SQLUtil.joinFileds(IAReportUtil.getRangeKeys(), "ia_calcrange"));
      
      sql.append(" from ia_detailledger, ia_calcrange ");
      sql.append(" where ia_detailledger.dr = 0");
      sql.append(" and ia_detailledger.ccalcrangeid = ia_calcrange.ccalcrangeid");
      sql.append(" and ia_detailledger.caccountperiod", ">=", accperfrom);
      sql.append(" and ia_detailledger.caccountperiod", "<=", accperto);
      sql.append(" and iauditsequence = -1");
      sql.append(gdsldgcon.getFilterSql());
      String resq7 = sql.toString();
      sql.append(gdsldgcon.getDefaultSql());
      String resq8 = sql.toString();
      if (gdsldgcon.getWheresql() != null && !gdsldgcon.getWheresql().contains("ctrantypeid")) {
    	  String param = gdsldgcon.getWheresql();
        sql.append(" and " + gdsldgcon.getWheresql());
      }
    } 
    sql.endParentheses();
    String resq9 = sql.toString();
    sql.append("ia_uniontable");
    
    sql.append(" order by cinventoryid,vbatchcode,ccalcrangeid,caccountperiod,");
    sql.append("case when iauditsequence = -1 then 2147483647 else iauditsequence end ,");
    
    sql.append("dbizdate,dbilldate,creationtime ");
    String resql = sql.toString();
    return sql.toString();
  }


  
  private String getgoodsldgdataQuerySql(GoodsLdgConProcess detldgcon) {
    String accperfrom = detldgcon.getAccPeriodFrom();
    String accperto = detldgcon.getAccPeriodTo();
    
    return getDetldgQuerySql(detldgcon, accperfrom, accperto);
  }

  
  private MetaData getMetaData() {
    List<Field> list = new ArrayList<Field>();
    GoodsLedgerViewVO view = new GoodsLedgerViewVO();
    IDataViewMeta viewmeta = view.getMetaData();
    for (String key : GoodsLedgerViewMeta.GOODSLDGFIELDS) {
      Field field = ReportDataUtil.createFiled(viewmeta, key);
      list.add(field);
    } 
    for (String key : GoodsLedgerViewMeta.CCALCRANGEID) {
      Field field = ReportDataUtil.createFiled(viewmeta, key);
      list.add(field);
    } 
    for (String key : StorLedgerViewMeta.STRINGFIELDS) {
      Field field = ReportDataUtil.createStringFiled(key);
      list.add(field);
    } 
    for (String key : GoodsLedgerViewMeta.DOUBLEFIELDS) {
      Field field = ReportDataUtil.createDoubleField(key);
      list.add(field);
    } 
    for (String key : GoodsLedgerViewMeta.INTEGERFIELDS) {
      Field field = ReportDataUtil.createIntegerFiled(key);
      list.add(field);
    } 
    
//    Field field = ReportDataUtil.createStringFiled("ctrantypeid");
//    list.add(field);
    
    Field[] fields = new Field[list.size()];
    list.toArray(fields);
    return new MetaData(fields);
  }
  
  private MetaData getMetaData2() {
	    List<Field> list = new ArrayList<Field>();
	    GoodsLedgerViewVO view = new GoodsLedgerViewVO();
	    IDataViewMeta viewmeta = view.getMetaData();
	    for (String key : GoodsLedgerViewMeta.GOODSLDGFIELDS) {
	      Field field = ReportDataUtil.createFiled(viewmeta, key);
	      list.add(field);
	    } 
	    for (String key : GoodsLedgerViewMeta.CCALCRANGEID) {
	      Field field = ReportDataUtil.createFiled(viewmeta, key);
	      list.add(field);
	    } 
	    for (String key : StorLedgerViewMeta.STRINGFIELDS) {
	      Field field = ReportDataUtil.createStringFiled(key);
	      list.add(field);
	    } 
	    for (String key : GoodsLedgerViewMeta.DOUBLEFIELDS) {
	      Field field = ReportDataUtil.createDoubleField(key);
	      list.add(field);
	    } 
	    for (String key : GoodsLedgerViewMeta.INTEGERFIELDS) {
	      Field field = ReportDataUtil.createIntegerFiled(key);
	      list.add(field);
	    }
	    
	    Field field = ReportDataUtil.createStringFiled("ctrantypeid");
	    list.add(field);
	    
	    Field[] fields = new Field[list.size()];
	    list.toArray(fields);
	    return new MetaData(fields);
	  }
  
  private String getThreadID(String cdetailledgerid) {
    SqlBuilder sql = new SqlBuilder();
    sql.append(" (select fcalcthreadbizflag,ccalcthreadid,ccalcid");
    sql.append(" from ia_detailledger detail");
    sql.append(" where cdetailledgerid", cdetailledgerid);
    sql.append(") union all  ");
    sql.append(" (select fcalcthreadbizflag,ccalcthreadid,ccalcid");
    sql.append(" from ia_hisdetailledger detail");
    sql.append(" where cdetailledgerid", cdetailledgerid);
    sql.append(")");
    DataAccessUtils dao = new DataAccessUtils();
    IRowSet rowset = dao.query(sql.toString());
    rowset.next();
    Integer fcalcthreadflag = rowset.getInteger(0);
    String ccalcthreadid = rowset.getString(1);
    if (!FCalcBizFlag.FCSP.equals(ValueUtils.getUFFlag(FCalcBizFlag.class, fcalcthreadflag)))
    {
      ccalcthreadid = rowset.getString(2);
    }
    return ccalcthreadid;
  }






  
  private void initCunit(GoodsLdgDataProcess goodsldgdata, String cinventory) {
    String cunit = null;
    
    SqlBuilder sql = new SqlBuilder();
    sql.append(" select pk_measdoc from  bd_material ");
    sql.append(" where ");
    sql.append("pk_material", cinventory);
    
    DataAccessUtils util = new DataAccessUtils();
    IRowSet iRow = util.query(sql.toString());
    if (iRow.next()) {
      cunit = iRow.getString(0);
    }
    goodsldgdata.initCunit(cunit);
  }




  
  private void queryBeginData(GoodsLdgConProcess detldgcon, GoodsLdgDataProcess goodsldgdata) {
    initCunit(goodsldgdata, detldgcon.getCinventory());
    List<GoodsLedgerViewVO> listdata = new ArrayList<GoodsLedgerViewVO>();
    
    String pk_org = detldgcon.getPk_org();
    String pk_book = detldgcon.getPk_book();
    Calendar calendar = Calendar.getInstance(pk_org, pk_book);
    String accfrom = detldgcon.getAccPeriodFrom();
    AccountPeriod accperfrom = calendar.getPeriod(accfrom);
    AccountPeriod sysstartper = calendar.getStartPeriod();
    
    SqlBuilder sql = new SqlBuilder();
    
    if (accperfrom.equals(sysstartper)) {
      accfrom = calendar.getQCPeriod();
    } else {
      
      accfrom = calendar.getPrevPeriod(accperfrom).toString();
    } 
    String calcrangeTable = "ia_calcrange.";
    
    sql.append("select ia_goodsmonthnab.nabnum, ");
    sql.append(" (ia_goodsmonthnab.nabmny),");
    sql.append(" ia_goodsmonthnab.nabprice,");
    sql.append(" ia_goodsmonthnab.nabvarymny,");
    sql.append(" ia_goodsmonthnab.cinventoryid,");
    sql.append(" ia_goodsmonthnab.ccustomerid,");
    sql.append(" ia_calcrange.vbatchcode,ia_calcrange.ccalcrangeid ");
    for (String key : GoodsLedgerViewMeta.DEF_FIELD) {
      sql.append("," + calcrangeTable + key);
    }
    sql.append(" from ia_goodsmonthnab  ");
    sql.append(" inner join ia_calcrange  on ");
    sql.append(" ia_goodsmonthnab.ccalcrangeid = ia_calcrange.ccalcrangeid");
    sql.append(" where ");
    sql.append(" ia_goodsmonthnab.dr = 0");
    sql.append(" and ia_goodsmonthnab.pk_book", pk_book);
    sql.append(" and ia_goodsmonthnab.caccountperiod", accfrom);
    sql.append(detldgcon.getMonthldgFilterSql());
    if (detldgcon.getWheresql() != null && !detldgcon.getWheresql().contains("ctrantypeid")) {
      sql.append(" and " + detldgcon.getWheresql());
    }
    
    DataAccessUtils bo = new DataAccessUtils();
    String psl = sql.toString();
    
    IRowSet rowset = bo.query(psl);
    while (rowset.next()) {
      int index = 0;
      GoodsLedgerViewVO begindata = new GoodsLedgerViewVO();
      begindata.setVbillcode(NCLangResOnserver.getInstance().getStrByID("2014006_0", "02014006-0083"));
      
      begindata.setPk_org(detldgcon.getPk_org());
      begindata.setPkBook(detldgcon.getPk_book());
      begindata.setCinventoryid(detldgcon.getCinventory());
      begindata.setNabnum(rowset.getUFDouble(index++));
      begindata.setNabmny(rowset.getUFDouble(index++));
      begindata.setNabprice(rowset.getUFDouble(index++));
      begindata.setNabvarymny(rowset.getUFDouble(index++));
      if (rowset.getString(index++) == null) {
        continue;
      }
      begindata.setCcustomerid(rowset.getString(index++));
      begindata.setVbatchcode(rowset.getString(index++));
      
      begindata.setCcalcrangeid(rowset.getString(index++));
      begindata.setVfree1(rowset.getString(index++));
      begindata.setVfree2(rowset.getString(index++));
      begindata.setVfree3(rowset.getString(index++));
      begindata.setVfree4(rowset.getString(index++));
      begindata.setVfree5(rowset.getString(index++));
      begindata.setVfree6(rowset.getString(index++));
      begindata.setVfree7(rowset.getString(index++));
      begindata.setVfree8(rowset.getString(index++));
      begindata.setVfree9(rowset.getString(index++));
      begindata.setVfree10(rowset.getString(index++));
      begindata.setCprojectid(rowset.getString(index++));
      begindata.setCvendorid(rowset.getString(index++));
      begindata.setCproductorid(rowset.getString(index++));
      begindata.setCasscustid(rowset.getString(index++));
      begindata.setCffileid(rowset.getString(index++));
      listdata.add(begindata);
    } 
    goodsldgdata.initBeginAbData((GoodsLedgerViewVO[])listdata.toArray(new GoodsLedgerViewVO[0]));
  }


  
  private GoodsLedgerViewVO[] queryFHDDetailVOs(ReportQueryCondition condition, String ccalcthreadid) throws BusinessException {
    boolean binclnoauditflag = false;
    ConditionVO[] vos = (ConditionVO[])condition.getUserObject();
    for (ConditionVO con : vos) {
      String fieldcode = con.getFieldCode();
      if ("binclnoaudit".equals(fieldcode)) {
        String value = con.getValue();
        
        if (value.equals(UFBoolean.TRUE.toString()) || value
          .equals("true")) {
          binclnoauditflag = true;
        }
        break;
      } 
    } 
    String[] names = VOValueUtil.getAttributeNames(nc.vo.ia.detailledger.entity.DetailLedgerVO.class);
    SqlBuilder sql = new SqlBuilder();
    sql.append(" select ");
    sql.append(SQLUtil.joinFileds(names, "detail"));
    sql.append(" from ( ");
    sql.append(" select ");
    sql.append(SQLUtil.joinFileds(names, "ia_detailledger"));
    sql.append(" from ia_detailledger ");
    sql.append(" where dr=0");
    if (!binclnoauditflag) {
      sql.append(" and iauditsequence >= 0");
    }
    sql.append(" and ");
    sql.startParentheses();
    sql.append(" ccalcthreadid", ccalcthreadid);
    sql.append(" or ");
    sql.startParentheses();
    sql.append(" ccalcid", ccalcthreadid);
    FCalcBizFlag[] flags = { FCalcBizFlag.FCSP, FCalcBizFlag.FCSP_TUIHUI, FCalcBizFlag.FCSP_TUSUN };

    
    sql.append(" and fcalcbizflag", flags);
    sql.endParentheses();
    sql.endParentheses();
    sql.append(" union all ");
    sql.append(" select ");
    sql.append(SQLUtil.joinFileds(names, "ia_hisdetailledger"));
    sql.append(" from ia_hisdetailledger ");
    sql.append(" where dr=0");
    if (!binclnoauditflag) {
      sql.append(" and iauditsequence >= 0");
    }
    sql.append(" and ");
    sql.startParentheses();
    sql.append(" ccalcthreadid", ccalcthreadid);
    sql.append(" or ");
    sql.startParentheses();
    sql.append(" ccalcid", ccalcthreadid);
    sql.append(" and fcalcbizflag", flags);
    sql.endParentheses();
    sql.endParentheses();
    sql.endParentheses();
    sql.append(" detail");
    sql.append(" order by detail.caccountperiod,");
    sql.append("case when detail.iauditsequence = -1 then 2147483647 else detail.iauditsequence end ,");
    
    sql.append("detail.dbizdate,detail.dbilldate,detail.creationtime ");
    
    DataAccessUtils dao = new DataAccessUtils();
    IRowSet rowset = dao.query(sql.toString());
    ViewRowSetMap<GoodsLedgerViewVO> bo = new ViewRowSetMap<GoodsLedgerViewVO>(GoodsLedgerViewVO.class, names);
    
    return (GoodsLedgerViewVO[])bo.convert(rowset);
  }


  
  private void queryGoodsLedgerData(DataSet dataset, GoodsLdgConProcess detldgcon, GoodsLdgDataProcess goodsldgdata) {
    String querysql = getgoodsldgdataQuerySql(detldgcon);
    PageInfo info = PageInfo.REPORT_GOODSLEDGER;
    info.setSql(querysql);
    ViewDBPage viewDBPage = new ViewDBPage(GoodsLedgerViewVO.class, info);
    
    SecondaryPage secondaryPage = new SecondaryPage(viewDBPage, IAReportUtil.getReportReturnMaxCount());
    
    int count = 0;
    while (secondaryPage.hasNext() && count < IAReportUtil.getReportReturnMaxCount()) {
      GoodsLedgerViewVO[] viewvos = (GoodsLedgerViewVO[])secondaryPage.next();
      fillVoucher(viewvos);
      goodsldgdata.addDetLdgPageDatas(viewvos);
      
      viewvos = goodsldgdata.getCurrentDatas();
    } 
    
    GoodsLedgerViewVO[] viewvos = goodsldgdata.getCurrentDatas();
    setDataSet(dataset, viewvos, goodsldgdata);
  }

  
  private GdsLdgBatchInitData[] queryYearInitData(GoodsLdgConProcess detldgcon, String accperfrom, String accperto, Integer fIntransitFlag) {
    List<GdsLdgBatchInitData> listinitdata = new ArrayList<GdsLdgBatchInitData>();
    
    String calcrangeTable = "ia_calcrange.";
    SqlBuilder sql = new SqlBuilder();
    sql.append("select ia_goodsledger.cinventoryid,ia_calcrange.vbatchcode,");
    sql.append("ia_calcrange.ccalcrangeid,ia_goodsledger.ccustomerid,");
    for (String key : GoodsLedgerViewMeta.DEF_FIELD) {
      sql.append(calcrangeTable + key + ",");
    }
    sql.append("sum(ia_goodsledger.nnum),sum(ia_goodsledger.nmny), ");
    sql.append("sum(case when ia_goodsledger.fpricemodeflag = 5 then ");
    sql.append(" ia_goodsledger.nvarymny else 0 end )");
    sql.append("from ia_goodsledger ");
    sql.append("inner join ia_calcrange on ");
    sql.append(" ia_goodsledger.ccalcrangeid = ia_calcrange.ccalcrangeid");
    sql.append(" where ia_goodsledger.dr=0 ");
    sql.append(" and ia_goodsledger.caccountperiod", ">=", accperfrom);
    sql.append(" and ia_goodsledger.caccountperiod", "<=", accperto);
    sql.append(" and ia_goodsledger.fintransitflag", fIntransitFlag);
    sql.append(detldgcon.getYearFilterSql());
    sql.append(detldgcon.getGoodsldgDefaultSql());
    
    if (detldgcon.getWheresql() != null && !detldgcon.getWheresql().contains("ctrantypeid")) {
    	String prsql = detldgcon.getWheresql();
      sql.append(" and " + detldgcon.getWheresql());
    }else if(detldgcon.getWheresql() != null && detldgcon.getWheresql().contains("ctrantypeid")){
    	String resq = detldgcon.getWheresql().replace("ctrantypeid", "ia_goodsledger.ctrantypeid");
        sql.append(" and " + resq);
    }
    sql.append(" group by ia_goodsledger.cinventoryid,ia_calcrange.vbatchcode,ia_calcrange.ccalcrangeid,");
    for (String key : DetailLedgerViewMeta.DEF_FIELD) {
      sql.append(calcrangeTable + key + ",");
    }
    sql.append(" ia_goodsledger.ccustomerid");
    DataAccessUtils bo = new DataAccessUtils();
    String psql = sql.toString();
    IRowSet rowset = bo.query(sql.toString());
    while (rowset.next()) {
      String cinventory = rowset.getString(0);
      String vbatchcode = rowset.getString(1);
      String ccalcrangeid = rowset.getString(2);
      String ccustomerid = rowset.getString(3);
      GdsLdgBatchInitData initdata = new GdsLdgBatchInitData(cinventory, vbatchcode, ccalcrangeid, ccustomerid);

      
      initdata.setVfree1(rowset.getString(4));
      initdata.setVfree2(rowset.getString(5));
      initdata.setVfree3(rowset.getString(6));
      initdata.setVfree4(rowset.getString(7));
      initdata.setVfree5(rowset.getString(8));
      initdata.setVfree6(rowset.getString(9));
      initdata.setVfree7(rowset.getString(10));
      initdata.setVfree8(rowset.getString(11));
      initdata.setVfree9(rowset.getString(12));
      initdata.setVfree10(rowset.getString(13));
      initdata.setCprojectid(rowset.getString(14));
      initdata.setCvendorid(rowset.getString(15));
      initdata.setCproductorid(rowset.getString(16));
      initdata.setCasscustid(rowset.getString(17));
      initdata.setCffileid(rowset.getString(18));
      initdata.setInitNum(rowset.getUFDouble(19));
      initdata.setInitMny(rowset.getUFDouble(20));
      initdata.setInitVaryMny(rowset.getUFDouble(21));
      listinitdata.add(initdata);
    } 
    
    GdsLdgBatchInitData[] yearindatas = new GdsLdgBatchInitData[listinitdata.size()];
    listinitdata.toArray(yearindatas);
    return yearindatas;
  }


  
  private void queryYearInOutData(GoodsLdgConProcess goodsldgcon, GoodsLdgDataProcess goodsldgdata) {
    Integer iCredit = (Integer)FIntransitFlag.CREDIT.value();
    Integer iDebit = (Integer)FIntransitFlag.DEBIT.value();
    String pk_org = goodsldgcon.getPk_org();
    String pk_book = goodsldgcon.getPk_book();
    Calendar calendar = Calendar.getInstance(pk_org, pk_book);
    AccountPeriod sysstartper = calendar.getStartPeriod();
    String accfrom = goodsldgcon.getAccPeriodFrom();
    
    String yearstartmon = calendar.getFirstPeriod(accfrom);
    
    if (yearstartmon.equals(accfrom) || accfrom.equals(sysstartper.toString())) {
      return;
    }
    
    AccountPeriod accperfrom = calendar.getPeriod(accfrom);
    String prvperiod = calendar.getPrevPeriod(accperfrom).toString();


    
    GdsLdgBatchInitData[] initCreditdata = queryYearInitData(goodsldgcon, yearstartmon, prvperiod, iCredit);
    goodsldgdata.initYearCreditData(initCreditdata);

    
    GdsLdgBatchInitData[] initDebitdata = queryYearInitData(goodsldgcon, yearstartmon, prvperiod, iDebit);
    goodsldgdata.initYearDebitData(initDebitdata);
  }

  
  private void setDataSet(DataSet dataset, GoodsLedgerViewVO[] viewvos, GoodsLdgDataProcess detldgdata) {
    MetaData metadata = dataset.getMetaData();
    String[] fieldnames = metadata.getFieldNames();
    int ilength = fieldnames.length;
    List<Object[]> listdata = new ArrayList<Object[]>();
    for (GoodsLedgerViewVO view : viewvos) {
      Object[] value = new Object[ilength];
      for (int i = 0; i < ilength; i++) {
        value[i] = view.getAttributeValue(fieldnames[i]);
      }
      listdata.add(value);
    } 
    
    detldgdata.clearCurrentDatas();
    
    detldgdata.addLastgoodsldgdata();
    
    detldgdata.addNotUseBeginData();
    
    GoodsLedgerViewVO[] lastviewvos = detldgdata.getCurrentDatas();
    for (GoodsLedgerViewVO view : lastviewvos) {
      Object[] value = new Object[ilength];
      for (int i = 0; i < ilength; i++) {
        value[i] = view.getAttributeValue(fieldnames[i]);
      }
      listdata.add(value);
    } 
    
    Object[][] datas = new Object[listdata.size()][fieldnames.length];
    listdata.toArray(datas);
    dataset.setDatas(datas);
  }
  
  private String getWheresql(String wheresql) {
    String sql = wheresql.replace("vfree", "ia_calcrange.vfree");
    String consql1 = sql.replace("casscustid", "ia_calcrange.casscustid");
    String consql2 = consql1.replace("cvendorid", "ia_calcrange.cvendorid");
    String consql3 = consql2.replace("cprojectid", "ia_calcrange.cprojectid");
    String consql4 = consql3.replaceAll("cproductorid", "ia_calcrange.cproductorid");
    
    return consql4.replace("cffileid", "ia_calcrange.cffileid");
  }
}